<template>
  <div class="p-4">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[18px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入排班名称" clearable />
            </el-form-item>
            <el-form-item label="设备状态" prop="onLine">
              <el-select v-model="queryParams.onLine" placeholder="请选择状态" clearable>
                <el-option v-for="dict in device_on_line" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="mac" prop="mac">
              <el-input v-model="queryParams.mac" placeholder="请输入mac" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb-[15px]">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="deviceList" row-key="id">
        <el-table-column prop="name" label="设备名称"></el-table-column>
        <el-table-column prop="mac" align="center" label="mac"></el-table-column>
        <el-table-column prop="onLine" align="center" label="设备状态">
          <template #default="scope">
            <dict-tag :options="device_on_line" :value="scope.row.onLine" />
          </template>
        </el-table-column>
        <el-table-column prop="status" align="center" label="是否激活">
          <template #default="scope">
            <dict-tag :options="device_active_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column prop="sort" align="center" label="排序"></el-table-column>
        <el-table-column fixed="right" align="center" label="操作" style="width: 300px">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['system:deviceInfo:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="SuitcaseLine" @click="handleDetail(scope.row)" />
            </el-tooltip>
            <el-tooltip content="设置统一温度" placement="top">
              <el-button link type="primary" icon="Odometer" @click="setTem(scope.row)" />
            </el-tooltip>
            <el-tooltip content="设置环境温度" placement="top">
              <el-button link type="primary" icon="Stopwatch" @click="setEnv(scope.row)" />
            </el-tooltip>
            <el-tooltip content="设置电流" placement="top">
              <el-button link type="primary" icon="Lightning" @click="setElect(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:deviceInfo:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <el-drawer v-model="drawer.visible" :title="drawer.title" destroy-on-close append-to-body size="50%">
      <el-form ref="deviceFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编号" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="mac值" prop="mac">
          <el-input v-model="form.mac" placeholder="请输入mac值" />
        </el-form-item>
        <el-form-item label="设备状态" prop="onLine">
          <el-select v-model="form.onLine" placeholder="请选择设备状态" clearable :disabled="disabled">
            <el-option v-for="dict in device_on_line" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备激活状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择设备状态" clearable :disabled="disabled">
            <el-option v-for="dict in device_active_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="drawer1" title="详情" destroy-on-close append-to-body size="50%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="设备名称:">{{ form.name }}</el-form-item>
        <el-form-item label="mac:">{{ form.mac }}</el-form-item>
        <el-form-item label="设备状态:">
          <dict-tag :options="device_on_line" :value="form.onLine" />
        </el-form-item>
        <el-form-item label="统一温度:">{{ form.settingTemperatureBo?.value }}</el-form-item>
        <el-form-item label="环境温度:">{{ form.settingEnvironmentBo?.temperature }}</el-form-item>
        <el-form-item label="环境湿度:">{{ form.settingEnvironmentBo?.humidity }}</el-form-item>
        <el-form-item label="报警值:">{{ form.settingElectricBo?.value }}</el-form-item>
        <el-form-item label="报警灵敏度:">{{ form.settingElectricBo?.sensitivity }}</el-form-item>
        <el-form-item label="提醒时间:">{{ form.settingElectricBo?.remindTime }}</el-form-item>
        <el-form-item label="排序:">{{ form.sort }}</el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel">确 定</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="drawerTem" title="设置统一温度" destroy-on-close append-to-body size="30%">
      <el-form ref="formTemRef" :model="formTem" :rules="formTemRule" label-width="80px">
        <el-form-item label="温度" prop="value">
          <el-input v-model="formTem.value" placeholder="请输入统一温度" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitFormTem(formTem)">确 定</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="drawerEnv" title="设置环境温度" destroy-on-close append-to-body size="30%">
      <el-form ref="formEnvRef" :model="formEnv" :rules="formEnvRule" label-width="80px">
        <el-form-item label="环境温度" prop="temperature">
          <el-input v-model="formEnv.temperature" placeholder="请输入环境温度" />
        </el-form-item>
        <el-form-item label="环境湿度" prop="humidity">
          <el-input v-model="formEnv.humidity" placeholder="请输入环境湿度" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitFormEnv(formEnv)">确 定</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="drawerElect" title="设置电流" destroy-on-close append-to-body size="30%">
      <el-form ref="formElectRef" :model="formElect" :rules="formElectRule" label-width="100px">
        <el-form-item label="报警值" prop="value">
          <el-input-number v-model="formElect.value" :step="1" :min="0" :max="999" style="width: 100%" step-strictly />
        </el-form-item>
        <el-form-item label="报警灵敏度" prop="sensitivity">
          <el-input-number v-model="formElect.sensitivity" :step="1" :min="0" :max="99" style="width: 100%" step-strictly />
        </el-form-item>
        <el-form-item label="提醒时间" prop="remindTime">
          <el-input-number v-model="formElect.remindTime" :step="1" :min="0" :max="99" style="width: 100%" step-strictly />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitFormElect(formElect)">确 定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import {
  getUserDeviceList,
  getUserDeviceDetail,
  addUserDevice,
  updateDevice,
  deleteDevice,
  settingTemperature,
  settingEnvironment,
  settingElectric
} from '@/api/device/device';
import { DeviceVO, DeviceQuery, DeviceForm, DeviceItem, SettingQuery } from '@/api/device/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { device_on_line, device_active_status } = toRefs<any>(proxy?.useDict('device_on_line', 'device_active_status'));
const loading = ref(true);
const showSearch = ref(true);
const drawer = reactive<DialogOption>({
  visible: false,
  title: ''
});
const skuListData: DeviceItem = {
  id: null,
  name: null,
  icon: 'https://tdesign.gtimg.com/demo/demo-image-1.png',
  targetKey: null,
  maxValue: null,
  minValue: null,
  valueArr: null,
  fixedValue: null,
  targetType: null,
  unit: null,
  sort: null
};
const drawer1 = ref(false);
const drawerTem = ref(false);
const drawerEnv = ref(false);
const drawerElect = ref(false);
const formTemRef = ref<ElFormInstance>();
const formEnvRef = ref<ElFormInstance>();
const formElectRef = ref<ElFormInstance>();
const deviceList = ref<DeviceVO[]>([]);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const deviceFormRef = ref<ElFormInstance>();
const disabled = ref<boolean>(false);
const initFormData: DeviceForm = {
  id: undefined,
  name: undefined,
  sn: undefined,
  mac: undefined,
  onLine: undefined,
  categoryIds: undefined,
  brandId: undefined,
  sort: undefined,
  activationTime: undefined,
  status: undefined,
  targetId: undefined,
  details: undefined,
  items: [skuListData],
  settingTemperatureBo: null,
  settingElectricBo: null,
  settingEnvironmentBo: null
};
const data = reactive<PageData<DeviceForm, DeviceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    onLine: undefined,
    name: undefined,
    mac: null
  },
  rules: {
    name: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    sn: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
    mac: [{ required: true, message: '设备mac值不能为空', trigger: 'blur' }],
    onLine: [{ required: true, message: '设备状态不能为空', trigger: 'change' }],
    sort: [{ required: true, message: '设备排序不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '设备激活状态不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
/** 统一温度设置数据 */
const formTem = ref<SettingQuery>({
  deviceId: null,
  value: null
});
const formTemRule = {
  value: [{ required: true, message: '统一温度不能为空', trigger: 'blur' }]
};
/** 温度和湿度设置数据 */
const formEnv = ref<SettingQuery>({
  deviceId: null,
  temperature: null,
  humidity: null
});
const formEnvRule = {
  temperature: [{ required: true, message: '温度不能为空', trigger: 'blur' }],
  humidity: [{ required: true, message: '湿度不能为空', trigger: 'blur' }]
};
/** 设置电流数据 */
const formElect = ref<SettingQuery>({
  deviceId: null,
  value: null,
  sensitivity: null,
  remindTime: null
});
const formElectRule = {
  value: [{ required: true, message: '报警值不能为空', trigger: 'blur' }],
  sensitivity: [{ required: true, message: '报警灵敏度不能为空', trigger: 'blur' }],
  remindTime: [{ required: true, message: '提醒时间不能为空', trigger: 'blur' }]
};

/** 查询用户设备列表 */
const getList = async () => {
  loading.value = true;
  const res = await getUserDeviceList(queryParams.value);
  deviceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  drawer.visible = false;
  drawer1.value = false;
  drawerTem.value = false;
  drawerEnv.value = false;
  drawerElect.value = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deviceFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  disabled.value = false;
  drawer.visible = true;
  drawer.title = '添加设备';
};

/** 修改按钮操作 */
const handleUpdate = async (row: DeviceVO) => {
  reset();
  const res = await getUserDeviceDetail(row.id);
  res.data.status = `${res.data.status}`;
  res.data.onLine = `${res.data.onLine}`;
  form.value = res.data;
  drawer.visible = true;
  drawer.title = '修改设备';
  disabled.value = true;
};

/** 提交按钮 */
const submitForm = () => {
  deviceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.id ? await updateDevice(form.value) : await addUserDevice(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      drawer.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: DeviceVO) => {
  await proxy?.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项?');
  await deleteDevice(row.id);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 详情 */
const handleDetail = async (row: DeviceVO) => {
  reset();
  const res = await getUserDeviceDetail(row.id);
  form.value = res.data;
  drawer1.value = true;
};
/** 设置统一温度 */
const setTem = (row: DeviceVO) => {
  drawerTem.value = true;
  formTem.value.deviceId = row.id;
  formTem.value.value = null;
};
const submitFormTem = async (row: SettingQuery) => {
  formTemRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      await settingTemperature(row);
      proxy?.$modal.msgSuccess('设置成功');
      drawerTem.value = false;
      getList();
    }
  });
};

/** 设置温度湿度 */
const setEnv = (row: DeviceVO) => {
  drawerEnv.value = true;
  formEnv.value.deviceId = row.id;
  formEnv.value.temperature = null;
  formEnv.value.humidity = null;
};
const submitFormEnv = async (row: SettingQuery) => {
  formEnvRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      await settingEnvironment(row);
      proxy?.$modal.msgSuccess('设置成功');
      drawerEnv.value = false;
      getList();
    }
  });
};

/** 设置温度湿度 */
const setElect = (row: DeviceVO) => {
  drawerElect.value = true;
  formElect.value.deviceId = row.id;
  formElect.value.sensitivity = null;
  formElect.value.remindTime = null;
  formElect.value.value = null;
};
const submitFormElect = async (row: SettingQuery) => {
  formElectRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      await settingElectric(row);
      proxy?.$modal.msgSuccess('设置成功');
      drawerElect.value = false;
      getList();
    }
  });
};

onMounted(() => {
  getList();
});
</script>
<style scoped lang="scss">
::v-deep .el-upload--picture-card {
  width: 50px !important;
  height: 50px !important;
}
::v-deep .el-form-item--default .el-form-item__content {
  margin-left: 0 !important;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  --el-upload-list-picture-card-size: 50px !important;
  width: var(--el-upload-list-picture-card-size) !important;
  height: var(--el-upload-list-picture-card-size) !important;
}
</style>
